<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 182px">
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="平台单号" value="platform_no"></el-option>
            <el-option label="计划单号" value="plan_no"></el-option>
            <el-option label="来源单号" value="source_no"></el-option>
            <el-option label="备料单号" value="plan_no"></el-option>
            <el-option label="采购单号/SKU/备货PR" value="purchase_no_sku_source_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.skuInfo.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VSelect v-model="form.order_source" placeholder="订单来源" :options="options.order_source || []" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.department_name" placeholder="需求部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.destination_warehouse" placeholder="发货仓库" type="warehouse156" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.purchase_type" placeholder="供应商类型" :options="options.purchase_type || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.payment_type" placeholder="付款方式" :options="options.payment_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VGroup>
          <el-select v-model="form.user.type" style="width: 130px">
            <el-option label="采购人员" value="purchase_user_id"></el-option>
            <el-option label="供应商负责人员" value="director_id"></el-option>
          </el-select>
          <VCascader v-model="form.user.value" placeholder="人员" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.audit_status" placeholder="审核状态" :options="options.audit_status || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.prepare_type" placeholder="备货方式" :options="options.prepare_type || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_drawback" placeholder="是否退税" :options="options.is_drawback || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_change" placeholder="是否变更" :options="options.is_new || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.has_combination" placeholder="是否有组合sku" :options="options.has_combination || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.country" placeholder="国家" :options="options.country" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.purchase_label" placeholder="采购标签" :options="options.purchase_label || []" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.warehouse.type" class="w-28" @change="form.warehouse.value = []">
            <el-option label="需求仓平台" value="demand_warehouse"></el-option>
            <el-option label="需求仓库" value="plan_demand_warehouse"></el-option>
          </el-select>
          <VSelect v-if="form.warehouse.type === 'demand_warehouse'" v-model="form.warehouse.value" placeholder="请选择" :options="options.demand_warehouse" multiple collapse-tags
            style="min-width: 160px" />
          <VSelect v-else v-model="form.warehouse.value" placeholder="请选择" :options="options.plan_demand_warehouse" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.platform" :options="options.platform" multiple collapse-tags style="min-width: 160px" placeholder="平台" />
        <VGroup>
          <el-select v-model="form.new.type" style="width: 130px">
            <el-option label="是否新品" value="is_new"></el-option>
            <el-option label="是否特采" value="is_special_purchase"></el-option>
          </el-select>
          <VSelect v-model="form.new.value" placeholder="请选择" :options="options.is_new" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.is_dangerous" placeholder="是否危险品" :options="options.is_dangerous" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_accord" placeholder="是否需求不满足" :options="options.is_accord" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.demand_form" :options="options.demand_form" multiple collapse-tags style="min-width: 160px" placeholder="备库需求单类型" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="下单时间" value="create_time"></el-option>
            <el-option label="最后审核时间" value="audit_time"></el-option>
            <el-option label="需求时间" value="demand_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
        <VSelect v-model="form.is_custom_product" :options="options.is_custom_product" multiple collapse-tags filterable clearable style="min-width: 140px" placeholder="是否定制化" />
      </template>
      <template #toolbar_btns>
        <VAudit ref="auditRef" auth="/purchase/manage/audit/audit" field="p_id" url="/v1/purchase/purchase-process/batch-audit" type="primary" :tableRef="tableRef"
          :list="options.batch_audit_status" @success="query">
          <template #default="{ form }">
            <el-form-item label="驳回原因">
              <VSelect v-model="form.reject_reason" placeholder="请选择" :options="options.audit_reject_reason" class="w-full" />
            </el-form-item>
            <el-form-item label="驳回备注">
              <el-input v-model="form.audit_remark" type="textarea" :rows="5"></el-input>
            </el-form-item>
          </template>
        </VAudit>
        <VButton auth="/purchase/manage/audit/revoke" :loading="loadings.revoke" @click="handleBatch('revoke', row)">
          批量撤回
        </VButton>
        <VTotal :data="total"
          :options="[{ title: '下单SKU数量', key: 'sku_num' },{ title: '下单PCS数', key: 'total_num' }, { title: '产品总金额', key: 'total_price' }, { title: '采购总金额', key: 'total_purchase_price' }]"
          class="ml-auto" />
        <VExport auth="/purchase/manage/audit/derive" mainKey="p_id" name="purchase_audit" :tableRef="tableRef" class="ml-auto" />
      </template>
    </VTable>
    <VLog ref="logRef" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from './api'
import { getOption, supplier } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import VTotal from '@/components/VTotal'
import { resMessage } from '@/utils/res'
const router = useRouter()

const baseName = 'purchase'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: 'test', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})


// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const p_ids = selection.map(d => d.p_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    revoke: () => {
      ElMessageBox.confirm('是否确认撤回采购单？', '提示', {
        confirmButtonClass: 'messagebox-confirm-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.revoke({ p_ids }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    }
  }
  handle[name]()
}

// 单行操作
const auditRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { p_id } = row
  const showLoading = () => loadings[name + rowIndex] = true
  const closeLoading = () => loadings[name + rowIndex] = false
  const handle = {
    look: async () => {
      showLoading()
      try {
        await api.detail({ p_id })
        sessionStorage.setItem(`PREV_ROUTER:/manage/process/view/${p_id}`, '/manage/audit')
        router.push(`/manage/process/view/${p_id}`)
      } catch (error) {
        console.log('error', error)
      }
      closeLoading()
    },
    audit: () => {
      auditRef?.value.open([row])
    },
    revoke: () => {
      ElMessageBox.confirm('是否确认撤回采购单？', '提示', {
        confirmButtonClass: 'messagebox-confirm-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.revoke({ p_ids: [p_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, p_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 156 },
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    data: {
      new: { type: 'is_new', value: '' }, // 组合
      input: { type: 'purchase_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      user: { type: 'purchase_user_id', value: [] },
      warehouse: { type: 'demand_warehouse', value: [] },
      purchase_day: {},
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      width: 180, slots: {
        header: () => <div>采购单</div>,
        default: ({ row, rowIndex }) => <div>
          <VText value={row.purchase_no} type='link' copy onClick={() => handleRow('look', row, rowIndex)}></VText>
          <VText title='是否有组合sku' value={row.has_combination_name} />
          <el-link type='primary'  href={`https://trade.1688.com/order/new_step_order_detail.htm?orderId=${row.platform_order_no}`} target="_blank" class='bg-blue-100 px-1 rounded-md'>{row.platform_order_no}</el-link>
        </div>
      }
    },
    {
      width: 220, slots: {
        header: () => <div>需求信息</div>,
        default: ({ row }) => <div>
          <VText title='订单来源' value={row.order_source_name} />
          {row.demand_data ? <div>
            <VText title='来源订单号' value={row.demand_data.demand_no} />
            <VText title='需求单类型' value={row.demand_data.demand_form_name} />
            <VText title='需求部门' value={row.demand_data.department_name} />
          </div> : ''}
          <VText title='需求时间' value={row.demand_time}></VText>
          <VText title='需求仓库' value={row.demand_warehouse_name} />
          <VText title='是否变更' value={row.is_change_name} />
        </div>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>备货方式<br />发货仓库<br />目的国家</div>,
        default: ({ row }) => <div>
          <VText value={row.prepare_type_name} />
          <VText value={row.destination_warehouse_name} />
          <VText value={row.country_name} />
        </div>
      }
    },
    {
      width: 200, slots: {
        header: () => <div>备料信息</div>,
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
          {{
            default: (line) => (row.plan_data || []).map(d => <div class='w-full'>
          <VText title='备料单号' value={d.plan_no}></VText>
          <VText title='备料数量' value={d.plan_num}></VText>
          <VText title='预计到货时间' value={d.pre_factory_time}></VText>
            </div>)
          }}
        </VMore>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>供应商类型</div>,
        default: ({ row }) => row.purchase_type_name
      }
    },
    {
      width: 220, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
          <VText title='供应商' value={row.supplier_name} />
          <VText title='供应商id' value={row.supplier_code} />
          <VText title='供应商类型' value={row.purchase_type_name} />
          <VText title='结算方式' value={row.period_name} />
          <VText title='供应商管理人员' value={row.director_name} />
        </div>
      }
    },
    {
      width: 140, slots: {
        header: () => <div>产品信息</div>,
        default: ({ row, rowIndex }) => {
          const purchase_sku = row.purchase_sku || []
          return <div>
            {row.is_accord === 1 ? <el-tag size='small' type='danger' effect="dark" class='mb-1'>{row.is_accord_name}</el-tag> : ''}
            <div class='flex mb-1'>
              {row.is_new === 2 ? <el-tag type="success" effect="dark" size='small' class='mx-1'>新</el-tag> : ''}
              {row.is_special_purchase === 2 ? <el-tag type="danger" size='small' effect="dark">特</el-tag> : ''}
              {row.is_dangerous === 2 ? <svg t="1731396340885" class="-mt-[1px] ml-1" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7755" width="24" height="24"><path d="M426.14784 160.23552l-368.27136 628.736a102.4 102.4 0 0 0 88.35072 154.17344h736.54272a102.4 102.4 0 0 0 88.35072-154.17344l-368.2304-628.736a102.4 102.4 0 0 0-176.7424 0z" fill="#FADE14" p-id="7756"></path><path d="M545.54624 158.96576a61.44 61.44 0 0 1 21.95456 21.99552l368.27136 628.736a61.44 61.44 0 0 1-53.00224 92.48768H146.2272a61.44 61.44 0 0 1-53.00224-92.48768l368.2304-628.736a61.44 61.44 0 0 1 84.09088-21.99552z m-63.73376 28.34432l-2.6624 3.97312-368.27136 628.736a40.96 40.96 0 0 0 30.55616 61.44l4.79232 0.24576h736.54272a40.96 40.96 0 0 0 37.51936-57.42592l-2.17088-4.25984-368.27136-628.736a40.96 40.96 0 0 0-68.03456-3.97312z" fill="#333333" p-id="7757"></path><path d="M450.1504 397.47584a385.26976 385.26976 0 0 1-123.2896 123.2896l19.6608 23.7568c12.288-8.6016 24.576-17.6128 36.864-27.4432v85.1968c-1.6384 67.1744-20.48 119.1936-56.5248 156.8768l23.7568 21.2992c39.3216-44.6464 60.2112-104.0384 62.2592-178.176v-66.7648h277.2992v-28.672h-121.6512c16.384-13.9264 33.1776-31.1296 49.9712-50.7904v-21.2992h-158.1056c6.9632-9.8304 13.5168-20.0704 20.0704-30.72l-30.3104-6.5536z m79.872 109.3632H395.6736c15.9744-14.336 31.1296-29.9008 45.4656-46.6944h138.8544c-16.384 17.6128-33.1776 33.1776-49.9712 46.6944z m73.728 101.5808v38.0928c0 13.1072-5.3248 19.6608-15.9744 19.6608-14.7456 0-31.1296-0.8192-49.152-2.4576l6.9632 27.8528c17.2032 0.8192 34.816 1.2288 52.8384 1.2288 23.3472-0.8192 35.2256-13.5168 35.2256-37.2736v-73.3184h-169.1648v153.6c0 24.576 13.1072 36.864 40.1408 36.864h129.4336c23.3472 0 39.3216-3.6864 47.5136-10.24 9.0112-8.192 15.1552-30.72 18.8416-66.7648l-28.2624-9.0112c-2.4576 23.7568-5.7344 39.7312-10.6496 47.9232-4.5056 6.9632-16.384 10.6496-35.2256 10.6496h-109.7728c-14.7456 0-22.1184-6.5536-22.1184-19.2512v-117.5552h109.3632z" fill="#333333" p-id="7758"></path></svg> : ''}
            </div>
            {purchase_sku.slice(0, 2).map(d => <div>{d}</div>)}
            {purchase_sku.length ? <el-button link type='primary' loading={loadings['look' + rowIndex]} onClick={() => handleRow('look', row, rowIndex)}>查看详情</el-button> : ''}
          </div>
        }
      }
    },
    {
      title: '图片', width: 100, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="80px"></VImage>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>下单数量</div>,
        default: ({ row }) => row.purchase_num
      }
    },
    {
      width: 170, slots: {
        header: () => <div>金额</div>,
        default: ({ row }) => {
          // 是否退税1否2是
          const { is_drawback, total_purchase_price, total_purchase_price_tax, total_price, total_price_tax } = row
          return <div>
            <VText title='产品总金额'>{is_drawback ? total_price : total_price_tax}</VText>
            <VText title='运费'>{row.tracking_price}</VText>
            <VText title='优惠'>{row.discount_price}</VText>
            <VText title='采购总金额'>{is_drawback === 1 ? total_purchase_price : total_purchase_price_tax}</VText>
          </div>
        }
      }
    },
    {
      width: 260, slots: {
        header: () => <div>负责人员</div>,
        default: ({ row }) => <div>
          <VText title='采购人员' value={row.purchase_user_name} />
          <VText title='下单时间'>{row.create_time}</VText>
          <VText title='最后审核时间'>{row.audit_time}</VText>
          <VText title='预计到货时间' value={row.expect_delivery_time}></VText>
        </div>
      }
    },
    {
      width: 130, slots: {
        header: () => <div>审核状态</div>,
        default: ({ row }) => <div>
          <div>{row.audit_status_name}</div>
          {row.next_audit_role_name ? <VText value={`待${row.next_audit_role_name}审核`} line={3} /> : ''}
        </div>
      }
    },
    {
      width: 120, slots: {
        header: () => <div>备注</div>,
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      width: 120, slots: {
        header: () => <div>驳回原因</div>,
        default: ({ row }) => <VText value={row.audit_remark} line={3} />
      }
    },
    {
      title: '操作', width: 80, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => <div class='nm flex flex-col gap-y-1'>
          <VButton auth="/purchase/manage/audit/audit" link type="primary" onClick={() => handleRow('audit', row, rowIndex)}>审核</VButton>
          <VButton auth="/purchase/manage/audit/revoke" link type="primary" onClick={() => handleRow('revoke', row, rowIndex)}>撤回</VButton>
          <VButton auth="/purchase/manage/audit/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
        </div>
      }
    }
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        api.total({ ...page, ...form }).then(res => {
          total.value = res.data
        })
        return api.query({ ...form, ...page })
      }
    }
  }
})

// 统计数据
const total = ref({})

</script>